/*
*   此商城的的聊天系统采用uniapp官方websocket api： https://uniapp.dcloud.io/api/request/websocket
*   uni.connectSocket  建立链接
*   uni.onSocketOpen   监听WebSocket连接打开事件
*   uni.onSocketMessage  监听WebSocket接受到服务器的消息事件
*   uni.sendSocketMessage  通过 WebSocket 连接发送数据
*  */
import {LIVESOKECT} from "./../config/index";
let timer = null;

const im =  () =>{
    uni.connectSocket({
        url: LIVESOKECT,
        header: {
            'content-type': 'application/json'
        },
        method: 'GET',
        success: res => {
            // console.log(`Websocket尝试连接${LIVESOKECT}✅...`)
        },
        fail: res => {
			console.log(res)
            console.log(`${LIVESOKECT}连接尝试失败❌`)
        }
    })

    uni.onSocketOpen(() => {
        console.info(`${LIVESOKECT} 连接打开onSocketOpen 开启心跳机制💚...`);
        timer = setInterval(() => {
            uni.sendSocketMessage({
                data: JSON.stringify({
                    type: "ping",
                    id: uni.getStorageSync("token"),
                }),
            });
        }, 9000);
    });


    uni.onSocketMessage((res) => {
        const data = JSON.parse(res.data);
        // console.log('websocket持续心跳中💚...',data)  需要测试时再打开
        if (data.type === "init") {
            const  client_id= data.data.client_id
            uni.sendSocketMessage({
                data: JSON.stringify({
                    type: "bind_id",
                    id: uni.getStorageSync("token"),
                    client_id,
                }),
            });
            uni.setStorageSync('client_id',client_id)
        }

        if (data.type === "say") {
            var pages = getCurrentPages();
            var page = pages[pages.length - 1];
            uni.vibrateLong({
                success: function() {
                    console.log("success");
                },
            });
        }
    });

    uni.onSocketClose(res=> {
        clearInterval(timer);
        console.log("-> ", res);
        console.log("WebSocket 已关闭！");
        im();
    });
    uni.onSocketError(res=> {
        clearInterval(timer);
        // console.error(`📵${LIVESOKECT}WebSocket连接打开失败，请检查！`);
        im();
    });
}
export default  im
